package com.bwie.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.*;
import com.bwie.common.domain.request.ActivityRequest;
import com.bwie.common.domain.response.ActivityProductListResponse;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.exception.ActivityException;
import com.bwie.mapper.ActivityMapper;
import com.bwie.service.ActivityService;
import com.bwie.stutas.Status;
import com.bwie.util.CreateCodeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.parser.Token;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @className: ActivityServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 刘茂锴
 * @date: 2025/10/2 11:16
 */
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CreateCodeUtil createCodeUtil;
    //拼团列表
    @Override
    public PageResult<ActivityProductListResponse> activityList(ActivityRequest activityRequest) {
        PageHelper.startPage(activityRequest.getPageNum(),activityRequest.getPageSize());
        List<ActivityProductListResponse> list=activityMapper.activityList(activityRequest);
        PageInfo<ActivityProductListResponse> info = new PageInfo<>(list);
        return PageResult.toPageResult(info.getTotal(), info.getList());
    }

    //商品下拉框
    @Override
    public List<Product> productList() {
        return activityMapper.productList();
    }

    //添加拼团活动
    @Override
    public void activityAdd(GroupActivity groupActivity) {
        groupActivity.setStatus(Status.QI);
        groupActivity.setCreateTime(new Date());
        groupActivity.setEndTime(new Date());
        groupActivity.setUpdateTime(new Date());
        groupActivity.setStartTime(new Date());
        activityMapper.activityAdd(groupActivity);
    }

    //发起拼团
    @Override
    public void activityFaTuan(Integer activityId) {
        //根据当前拼团id 查询拼团
        GroupActivity groupActivity=activityMapper.selectActivity(activityId);

        //根据拼团id 查询会话
        GroupSession groupSession=activityMapper.selectGroupSession(groupActivity.getId());
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (user==null){
            throw new ActivityException("请您先登录");
        }
        int count=activityMapper.selectUserIdAndActivity(user.getId());
        if (count>1){
            throw new ActivityException("您已经拥有"+count+"个未完成的拼团了");
        }
        GroupOrder groupOrder = new GroupOrder();
        groupOrder.setActivityId(groupActivity.getId());
        groupOrder.setUserId(user.getId());
        groupOrder.setOrderNo("GO"+new Date());
        groupOrder.setProductId(groupActivity.getProductId());
        groupOrder.setQuantity(Status.TING);
        groupOrder.setTotalAmount(groupActivity.getGroupPrice());
        groupOrder.setPayAmount(groupActivity.getGroupPrice());
        groupOrder.setOrderStatus(Status.QI);
        groupOrder.setGroupStatus(Status.QI);
        groupOrder.setIsLeader(Status.TING);
        groupOrder.setGroupSessionId(groupSession.getId());
        groupOrder.setCreateTime(new Date());
        activityMapper.groupOrderAdd(groupOrder);
    }

    //参加拼团
    @Override
    public void activityCanTuan(Integer activityId) {
        // 分布式锁的key，使用活动ID确保同一活动的参团操作串行化
        String lockKey = "canTuan:lock:" + activityId;
        String lockValue = String.valueOf(System.currentTimeMillis());

        try {
            // 尝试获取分布式锁，设置过期时间为30秒
            Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, java.util.concurrent.TimeUnit.SECONDS);
            
            if (!lockAcquired) {
                throw new ActivityException("系统繁忙，请稍后重试");
            }
            
            // 获取当前用户信息
            String token = request.getHeader(TokenConstants.TOKEN);
            String userKey = JwtUtils.getUserKey(token);
            User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
            if (user == null) {
                throw new ActivityException("请您先登录");
            }
            
            // 查询拼团活动信息
            GroupActivity groupActivity = activityMapper.selectActivity(activityId);
            if (groupActivity == null) {
                throw new ActivityException("拼团活动不存在");
            }
            
            // 检查活动状态
            if (groupActivity.getStatus() != Status.TING) {
                rabbitTemplate.convertAndSend("2302A",activityId);
                throw new ActivityException("活动未开始或已结束");
            }
            
            // 检查活动库存
            if (groupActivity.getStock() <= Status.QI) {
                throw new ActivityException("活动库存不足");
            }
            //同一个团只能申请一次
            int i=activityMapper.selectUserActivity(user.getId(),groupActivity.getId());
            if (i>Status.TING){
                throw new ActivityException("你已经参加过该团了，不可重复参加");
            }
            // 查询团会话信息
            GroupSession groupSession = activityMapper.selectGroupSession(activityId);
            if (groupSession == null) {
                throw new ActivityException("团会话不存在");
            }
            
            // 检查团会话状态
            if (groupSession.getStatus() != Status.QI) {
                throw new ActivityException("该团已结束或已成功");
            }
            
            // 检查用户是否已在该团中
            int userInGroup = activityMapper.selectUserInGroupSession(user.getId(), groupSession.getId());
            if (userInGroup > Status.QI) {
                throw new ActivityException("您已参与该团，不能重复参团");
            }
            
            // 检查用户未完成拼团数量
            int userUnfinishedGroups = activityMapper.selectUserIdAndActivity(user.getId());
            if (userUnfinishedGroups >= Status.TING) {
                throw new ActivityException("您已有未完成的拼团，请先完成后再参团");
            }
            
            // 获取当前团人数
            int currentSize = activityMapper.selectGroupSessionCurrentSize(groupSession.getId());
            
            // 检查是否已满团
            if (currentSize >= groupSession.getGroupSize()) {
                throw new ActivityException("该团已满，请选择其他团");
            }
            
            // 创建参团订单
            GroupOrder groupOrder = new GroupOrder();
            groupOrder.setActivityId(groupActivity.getId());
            groupOrder.setUserId(user.getId());
            groupOrder.setOrderNo("GO" + System.currentTimeMillis());
            groupOrder.setProductId(groupActivity.getProductId());
            groupOrder.setQuantity(Status.TING);
            groupOrder.setTotalAmount(groupActivity.getGroupPrice());
            groupOrder.setPayAmount(groupActivity.getGroupPrice());
            groupOrder.setOrderStatus(Status.QI);
            groupOrder.setGroupStatus(Status.QI);
            groupOrder.setIsLeader(Status.QI); // 参团者不是团长
            groupOrder.setGroupSessionId(groupSession.getId());
            groupOrder.setCreateTime(new Date());
            
            // 保存订单
            activityMapper.groupOrderAdd(groupOrder);
            
            // 更新团会话当前人数
            int newCurrentSize = currentSize + Status.TING;
            activityMapper.updateGroupSessionCurrentSize(groupSession.getId(), newCurrentSize);
            
            // 检查是否成团
            if (newCurrentSize >= groupSession.getGroupSize()) {
                // 成团成功，更新团会话状态
                activityMapper.updateGroupSessionStatus(groupSession.getId(), Status.TING);

            }
            
        } finally {
            // 释放分布式锁
            String currentLockValue = (String) redisTemplate.opsForValue().get(lockKey);
            if (lockValue.equals(currentLockValue)) {
                redisTemplate.delete(lockKey);
            }
        }


    }


    public List<String>  generateQrcode(Set<Long> ids) {
        List<String> imgList = new ArrayList<>();
        ids.stream().forEach(k->{
            // 生成字节数组输出流
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();


            /*
            // 生成二维码
            QrCodeUtil.generate(content, //二维码内容
                    // setImg("image/2.jpg"), //附带logo+
                    QrConfig.create().setErrorCorrection(ErrorCorrectionLevel.H).setWidth(350).setHeight(350), "png", byteOut);
            */
            BufferedImage bufferedImage = createCodeUtil.encode("二维码内容", null, "二维码下面文字描述", null);

            try {
                ImageIO.write(bufferedImage, "png", byteOut);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 生成字节数组输入流
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
           /*
            // 从流中读取图片,返回图片文件
            BufferedImage img = ImgUtil.read(byteIn);

            // 将图片对象转换为Base64形式
            String base64 = ImgUtil.toBase64(img, "png");
           */

            String bucketName = "qrcode";
            String objectKey =k + ".png";
//            try {
//                minioStorageService.uploadByInputStream(bucketName,objectKey,byteIn,"image/png");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            imgList.add(bucketName + "/" + objectKey);
        });
        return imgList;
    }
//    public List<String> generateQrcode(Set<Long> ids) {
//        List<String> imgList = new ArrayList<>();
//
//        ids.stream().forEach(k -> {
//            // 生成字节数组输出流
//            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//
//            // ⭐需要修改的部分⭐
//            // 1. 二维码内容 - 根据你的业务需求设置
//            String qrContent = generateQrContent(k); // 根据ID生成二维码内容
//
//            // 2. 二维码下方文字 - 可自定义
//            String descText = "ID: " + k; // 二维码下方显示的文字
//
//            // 生成二维码图片
//            BufferedImage bufferedImage = createCodeUtil.encode(qrContent, null, descText, null);
//
//            try {
//                ImageIO.write(bufferedImage, "png", byteOut);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//
//            // ⭐选择存储方式⭐
//            // 方案A: 直接返回Base64给前端（推荐，简单快捷）
//            String base64 = Base64.getEncoder().encodeToString(byteOut.toByteArray());
//            imgList.add("data:image/png;base64," + base64);
//
//            // 方案B: 上传到MinIO（如果需要持久化存储）
//        /*
//        String bucketName = "qrcode";
//        String objectKey = k + ".png";
//        try {
//            minioStorageService.uploadByInputStream(bucketName, objectKey,
//                new ByteArrayInputStream(byteOut.toByteArray()), "image/png");
//            imgList.add(bucketName + "/" + objectKey);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        */
//        });
//        return imgList;
//    }
//
//    // ⭐新增方法：生成二维码内容⭐
//    private String generateQrContent(Long id) {
//        // 根据你的业务需求生成二维码内容，例如：
//        // 1. 跳转链接
//        return "https://your-domain.com/details?id=" + id;
//        // 2. 包含业务数据的字符串
//        // return "PRODUCT:" + id + ":" + System.currentTimeMillis();
//        // 3. 微信小程序路径等
//        // return "pages/detail/detail?id=" + id;
//    }


}




